extends Node

@export var player_scene: PackedScene
@export var bullet_scene: PackedScene
@export var enemy_regular_scene: PackedScene
@export var enemy_adv_scene: PackedScene

var player
var score

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	start_game()

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta: float) -> void:
	pass

func _on_regular_enemy_generate_timer_timeout() -> void:
	var enemy = enemy_regular_scene.instantiate()
	enemy.hit.connect(on_enemy_hit)
	enemy.position = Vector2(randi() % 500 + 30, 0)
	add_child(enemy)
	
func _on_adv_enemy_generate_timer_timeout() -> void:
	var enemy = enemy_adv_scene.instantiate()
	enemy.hit.connect(on_enemy_hit)
	enemy.position = Vector2(randi() % 500 + 30, 0)
	enemy.flying_direction = (player.global_position - enemy.global_position).normalized()
	add_child(enemy)
	
func on_player_fire() -> void:
	var bullet_left = bullet_scene.instantiate()
	var bullet_right = bullet_scene.instantiate()
	bullet_left.position = player.position + Vector2.RIGHT * 15
	bullet_right.position = player.position + Vector2.RIGHT * 65
	add_child(bullet_left)
	add_child(bullet_right)
	$FireAudio.play()
	
func on_player_hit_down() -> void:
	$PlayerDownAudio.play()
	stop_game()
	
func on_player_hit(player: Node) -> void:
	$CanvasLayer/ProgressBar.value = player.hp
	
func on_player_hp_increase(player: Node) -> void:
	$CanvasLayer/ProgressBar.value = player.hp

func on_enemy_hit(target: Node, enemy: Node):
	if target.is_in_group("bullets"):
		$SmallEnemyDownAudio.play()
		score += 1
		update_score()
		if score == 3:
			$AdvEnemyGenerateTimer.start()

func start_game():
	score = 0
	$CanvasLayer/GameOverLabel.visible = false
	# 初始化玩家战机实例
	player = player_scene.instantiate()
	# 将战机放置于指定的位置
	player.start($StartPosition.position)
	# 订阅战机的“开火”事件
	player.connect("fire", on_player_fire)
	# 订阅战机的“击落”事件
	player.connect("hit_down", on_player_hit_down)
	# 订阅战机的“击中”事件
	player.connect("hit", on_player_hit)
	# 订阅战机的“血量增加”事件
	player.connect("hp_increase", on_player_hp_increase)
	# 将战机添加到当前场景
	add_child(player)
	$CanvasLayer/ProgressBar.max_value = player.hp
	$CanvasLayer/ProgressBar.value = player.hp
	# 启动敌机生成逻辑
	$RegularEnemyGenerateTimer.start()
	# 开始播放背景音乐
	# $BGM.play()

func stop_game():
	$CanvasLayer/GameOverLabel.visible = true
	$RegularEnemyGenerateTimer.stop()
	$AdvEnemyGenerateTimer.stop()
	$BGM.stop()

func update_score():
	$CanvasLayer/ScoreLabel.text = "%06d" % score
